import axios from "axios";

const baseURL = process.env.NODE_ENV === "development" ? "/api" : "./";
// create an axios instance
const service = axios.create({
    baseURL: baseURL, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000, // request timeout
    headers: {"Content-Type": "application/json;charset=UTF-8"}, // 默认设置请求头 为FormData 数据格式  （JSON数据格式：application/json）
    method: "post"
});

// request拦截器 request interceptor
service.interceptors.request.use(
    config => {
        // config.transformRequest = [
        //   function(data = {}) {
        //     let query = {
        //       ...data
        //     };
        //     console.log(config.url, query);
        //     if (config.method == "get") {
        //       config.headers["Content-Type"] = "application/x-www-form-urlencoded";
        //       // config.params = { ...config.params };
        //     } else {
        //       config.headers["Content-Type"] = "application/json;charset=UTF-8";
        //       // config.data = qs.stringify(query);
        //     }
        //     return config;
        //   }
        // ];
        return config;
    },
    error => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);
// respone拦截器
service.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.status && res.status != 200) {
            return Promise.reject(res || "error");
        } else {
            return Promise.resolve(res);
        }
    },
    error => {
        return Promise.reject(error);
    }
);

export default service;
